package util

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"log"
	"net/http"
)

func HttpGetStringMap(http *http.Client, url string) (map[string]string, error) {
	res, err := http.Get(url)
	if err != nil || res == nil {
		log.Fatalf("http get %s fail, err=%s", url, err)
		return map[string]string{}, err
	}
	defer res.Body.Close()
	resBody, err := ioutil.ReadAll(res.Body)
	resMap := make(map[string]string)
	json.Unmarshal(resBody, &resMap)
	return resMap, nil
}

func HttpPostStringMap(http *http.Client, url string, body io.Reader) (map[string]interface{}, error) {
	res, err := http.Post(url, "application/json; charset=utf-8", body)
	if err != nil || res == nil {
		log.Fatalf("http post %s fail, err=%s", url, err)
		return nil, err
	}
	defer res.Body.Close()
	resBody, err := ioutil.ReadAll(res.Body)
	resMap := make(map[string]interface{})
	json.Unmarshal(resBody, &resMap)
	return resMap, nil
}

func MapPostBody(body map[string]interface{}) io.Reader {
	requestBody, err := json.Marshal(body)
	if err != nil {
		log.Fatalf("func MapPostBody json.Marshal fail, err:%s", err)
		return nil
	}
	return bytes.NewReader(requestBody)
}
